<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Enigo Universal Test</title>
</head>

<body>
    <h1>Conducted tests</h1>
    <!-- Checkbox to disable WebSocket connection -->
    <input type="checkbox" id="disableWS" name="disableWS" />
    <label for="disableWS"> Disable WebSocket Connection</label><br>
    <input type="checkbox" id="KeyDown" name="KeyDown">
    <label for="KeyDown"> KeyDown</label><br>
    <input type="checkbox" id="KeyUp" name="KeyUp">
    <label for="KeyUp"> KeyUp</label><br>
    <input type="checkbox" id="MouseDown" name="MouseDown">
    <label for="MouseDown"> MouseDown</label><br>
    <input type="checkbox" id="MouseUp" name="MouseUp">
    <label for="MouseUp"> MouseUp</label><br>
    <input type="checkbox" id="MouseMove" name="MouseMove">
    <label for="MouseMove"> MouseMove</label><br>
    <input type="checkbox" id="MouseScroll" name="MouseScroll">
    <label for="MouseScroll"> MouseScroll</label><br>
    <textarea id="text" name="text" rows="20" cols="50"></textarea><br>

    <script>
        let ws;
        let messageQueue = [];

        window.onload = () => {
            const textArea = document.getElementById('text');
            textArea.focus();
            // Only initialize the WebSocket if the disable checkbox is not checked
            if (!document.getElementById('disableWS').checked) {
                initializeWebSocket();
            }
        };

        // Listen for changes on the disable checkbox
        document.getElementById('disableWS').addEventListener('change', function () {
            if (!this.checked && (!ws || ws.readyState !== WebSocket.OPEN)) {
                console.log('WebSocket re-enabled via checkbox. Attempting to reconnect...');
                initializeWebSocket();
            }
        });


        // Initialize or reconnect WebSocket
        function initializeWebSocket() {
            console.log('Attempting to connect WebSocket...');
            ws = new WebSocket('ws://localhost:26541');

            ws.addEventListener('open', () => {
                console.log('WebSocket connected');
                flushMessageQueue();
            });

            ws.addEventListener('close', () => {
                console.warn('WebSocket disconnected. Retrying...');
                scheduleReconnect();
            });

            ws.addEventListener('error', (error) => {
                console.error('WebSocket error:', error);
                scheduleReconnect();
            });
        }

        function scheduleReconnect() {
            if (document.getElementById('disableWS').checked) {
                console.log('WebSocket connection is disabled by checkbox.');
                return;
            }
            setTimeout(() => {
                // Only try to reconnect if still not connected
                if (!ws || ws.readyState !== WebSocket.OPEN) {
                    initializeWebSocket();
                }
            }, 1000); // Retry every 1000 milliseconds (1 second)
        }

        function sendMessage(obj) {
            const json = JSON.stringify(obj);
            // Log all properties of the event before conversion
            console.log("send message:", json);
            // Queue a message or send it directly if WebSocket is connected
            if (ws && ws.readyState === WebSocket.OPEN) {
                ws.send(json);
            } else {
                messageQueue.push(json);
            }
        }

        function flushMessageQueue() {
            while (messageQueue.length > 0) {
                ws.send(messageQueue.shift());
            }
        }

        function handleAndSend(e) {
            const textArea = document.getElementById('text');
            const text = textArea.value;

            let token = { type: e.type, timestamp: e.timeStamp };

            switch (e.type) {
                case "keydown":
                case "keyup":
                    token.key = e.key;
                    token.code = e.code;
                    token.keyCode = e.keyCode;
                    token.altKey = e.altKey;
                    token.ctrlKey = e.ctrlKey;
                    token.shiftKey = e.shiftKey;
                    token.metaKey = e.metaKey;
                    token.direction = (e.type === "keydown") ? "pressed" : "released";
                    token.type = "key";
                    break;

                case "mousedown":
                case "mouseup":
                    token.button = e.button;
                    token.buttons = e.buttons;
                    token.clientX = e.clientX;
                    token.clientY = e.clientY;
                    token.screenX = e.screenX;
                    token.screenY = e.screenY;
                    token.direction = (e.type === "mousedown") ? "pressed" : "released";
                    token.type = "button";
                    break;

                case "mousemove":
                    token.clientX = e.clientX;
                    token.clientY = e.clientY;
                    token.movementX = e.movementX;
                    token.movementY = e.movementY;
                    token.type = "mouseMove";
                    break;

                case "wheel":
                    token.deltaX = e.deltaX;
                    token.deltaY = e.deltaY;
                    token.deltaMode = e.deltaMode;
                    token.clientX = e.clientX;
                    token.clientY = e.clientY;
                    token.type = "scroll";
                    break;
            }

            // 🔹 Clear the textarea after each keyup
            if (e.type === "keyup") {
                textArea.value = "";
            }

            const msg = { text, event: token };
            console.log("prepared message:", msg);
            sendMessage(msg);

        }



        ["keydown", "keyup", "mousedown", "mouseup", "mousemove", "wheel"].forEach(evt =>
            document.addEventListener(evt, handleAndSend)
        );
    </script>

</body>

</html>